
using AutoMapper;
using Coldairarrow.Util;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Util;

namespace API.Controllers
{
    public class CanteenMenuController : BaseController
    {
        Repository<tCanteenMenu> _CanteenMenu;
        Repository<tMealReporting> _MealReporting;
        Repository<tSignIn> _SignIn;
        Repository<tFoodProcure> _food;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public CanteenMenuController(Repository<tCanteenMenu> CanteenMenu, IMapper mapper, Repository<tMealReporting> mealReporting, Repository<tSignIn> signIn, ISqlSugarClient db, Repository<tFoodProcure> food)
        {
            _CanteenMenu = CanteenMenu;
            _mapper = mapper;
            _MealReporting = mealReporting;
            _SignIn = signIn;
            _db = db;
            _food = food;
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="filePath"></param>
        /// <exception cref="NotSupportedException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<string>> ImportExcelFile([FromForm] IFormCollection formCollection)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                List<string> filelist = new List<string>();
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                if (fileCollection != null && fileCollection.Count > 0)
                {
                    filelist = UploadOperate.UploadSteam(fileCollection, AppContext.BaseDirectory + "\\menu\\");
                }
                string currentDirectory = Directory.GetCurrentDirectory();
                string filePath = AppContext.BaseDirectory + "\\menu\\" + filelist[0];
                // 根据文件路径创建文件流  
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    // 根据文件流创建工作簿对象  
                    IWorkbook workbook;
                    if (Path.GetExtension(filePath) == ".xls")
                    {
                        workbook = new HSSFWorkbook(stream);
                    }
                    else if (Path.GetExtension(filePath) == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(stream);
                    }
                    else
                    {
                        throw new NotSupportedException("不支持的文件格式");
                    }

                    // 获取第一个工作表  
                    ISheet sheet = workbook.GetSheetAt(0);
                    if (sheet == null) throw new ArgumentNullException("工作表为空");
                    List<tCanteenMenu> list = new List<tCanteenMenu>();
                    // 遍历行和列，读取数据  
                    for (int row = 1; row <= sheet.LastRowNum; row++)
                    {
                        if (sheet.GetRow(row) == null) continue; // 跳过空行  

                        ICell cell = sheet.GetRow(row).GetCell(0);
                        var MTime = cell.DateCellValue;
                        var model = await _CanteenMenu.GetListAsync(x => x.FMTime == MTime && x.FMType == 1);
                        if (model != null)
                        {
                           await _CanteenMenu.DeleteAsync(model);
                        }
                        cell = sheet.GetRow(row).GetCell(1);
                        var WeekDay = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(2);
                        var MName = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(3);
                        var MName2 = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(4);
                        var MName3 = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(5);
                        var Soup = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(6);
                        var Syrup = cell.StringCellValue;
                        var menu=new tCanteenMenu();
                        //过滤掉菜单式空的数据
                        if (!string.IsNullOrEmpty(MName) && !string.IsNullOrEmpty(MName2) && !string.IsNullOrEmpty(MName3))
                        {
                            menu = new tCanteenMenu();
                            menu.FMTime = MTime;
                            menu.FWeekDay = WeekDay;
                            menu.CreatorId = CurrentUserId;
                            menu.CreateTime = DateTime.Now;
                            menu.FMName = MName;
                            menu.FMName2 = MName2;
                            menu.FMName3 = MName3;
                            menu.FSoup = Soup;
                            menu.FSyrup = Syrup;
                            menu.FMType = 1;
                            menu.FDeleted = false;
                            InitEntity(menu);
                            list.Add(menu);
                        }
                        model = _CanteenMenu.GetList(x => x.FMTime == MTime && x.FMType == 2);
                        if (model != null)
                        {
                            _CanteenMenu.Delete(model);
                        }
                        cell = sheet.GetRow(row).GetCell(7);
                        var MName4 = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(8);
                        var MName5 = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(9);
                        var MName6 = cell.StringCellValue;
                        cell = sheet.GetRow(row).GetCell(10);
                        var Soup2 = cell.StringCellValue;
                        //过滤掉菜单式空的数据
                        if (!string.IsNullOrEmpty(MName4) && !string.IsNullOrEmpty(MName5) && !string.IsNullOrEmpty(MName6))
                        {
                            menu = new tCanteenMenu();
                            menu.FMTime = MTime;
                            menu.FWeekDay = WeekDay;
                            menu.CreatorId = CurrentUserId;
                            menu.CreateTime = DateTime.Now;
                            menu.FMName = MName4;
                            menu.FMName2 = MName5;
                            menu.FMName3 = MName6;
                            menu.FSoup = Soup2;
                            menu.FSyrup = "";
                            menu.FMType = 2;
                            menu.FDeleted = false;
                            InitEntity(menu);
                            list.Add(menu);
                        }
                    }
                    await _CanteenMenu.InsertRangeAsync(list);

                    return result.Success("导入成功");
                }
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-Save:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <param name="input">12345</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save(SaveCanteenMenuInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = await _CanteenMenu.GetFirstAsync(x => x.FMType == input.MType && x.FMTime == input.MTime);
                if (model == null)
                {
                    await _CanteenMenu.InsertAsync(new tCanteenMenu
                    {
                        FMTime = input.MTime,
                        FWeekDay = input.WeekDay,
                        CreatorId = CurrentUserId,
                        CreateTime = DateTime.Now,
                        FMName = input.MName,
                        FMName2 = input.MName2,
                        FMName3 = input.MName3,
                        FSoup = input.Soup,
                        FSyrup = input.Syrup,
                        FMType = input.MType,
                        Id=IdHelper.GetId()
                    });
                }
                else
                {
                    model.FMTime = input.MTime;
                    model.FWeekDay = input.WeekDay;
                    model.FMName = input.MName;
                    model.FMName2 = input.MName2;
                    model.FMName3 = input.MName3;
                    model.FSoup = input.Soup;
                    model.FSyrup = input.Syrup;
                    model.FMType = input.MType;
                    await _CanteenMenu.UpdateAsync(model);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-Save:" + ex);
                return result.Exception();
            }
        }
        [HttpPost]
        /// <summary>
        /// 通过ID删除数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ResultMsg<string>> DeleteById(int Id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _CanteenMenu.DeleteByIdAsync(Id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-DeleteById:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取当前周菜单(员工查看)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<StaffMealRepOutput>>> GetMeenListByUserId(GetMeenListByUserIdInput input)
        {
            ResultMsg<List<StaffMealRepOutput>> result = new ResultMsg<List<StaffMealRepOutput>>();
            try
            {
                var list = new List<tCanteenMenu>();

                Common commonInstance = new Common(_db); // 使用db实例化Common类
                List<StaffMealRepOutput> menus = new List<StaffMealRepOutput>();
                StaffMealRepOutput dao = new StaffMealRepOutput();
                if (input != null)
                {
                    if (input.FirstDay > input.LastDay)
                    {
                        return result.Error("开始时间不能大于结束时间");
                    }
                    for (int i = 0; i < 7; i++)
                    {
                        menus.Insert(i, new StaffMealRepOutput
                        {
                            WeekDay = commonInstance.GetDayOfWeek(input.FirstDay.AddDays(i)),
                            MTime = input.FirstDay.AddDays(i).ToString("yyyy-MM-dd"),
                        });
                    }
                    list = (await _CanteenMenu.GetListAsync(x => x.FMTime >= input.FirstDay && x.FMTime <= input.LastDay)).OrderBy(c => c.FMTime).ToList();
                    if (list.Count == 0)
                        return result.Error("当前菜单还没创建，请耐心等待!");
                   
                    var lunch_start = commonInstance.GetConfig().LunchStartScan;
                    var lunch_end = commonInstance.GetConfig().LunchEndScan;
                    var dinner_start = commonInstance.GetConfig().DinnerStartScan;
                    var dinner_end = commonInstance.GetConfig().DinnerEndScan;
                    var lunchTime = commonInstance.GetConfig().Lunch;
                    var dinnerTime = commonInstance.GetConfig().Dinner;
                    foreach (var item in menus)
                    {
                        foreach (var menu in list.Where(x => x.FMType == 1))
                        {
                            if (item.MTime == menu.FMTime.ToString("yyyy-MM-dd"))
                            {
                                item.WeekDay = menu.FWeekDay;
                                //item.MTime = menu.MTime.ToString("yyyy-MM-dd");
                                item.MName = menu.FMName;
                                item.MName2 = menu.FMName2;
                                item.MName3 = menu.FMName3;
                                item.Soup = menu.FSoup;
                                item.Syrup = menu.FSyrup;
                                item.LRep = (await _MealReporting.CountAsync(x => x.FEID == input.UserId && x.FRTime == menu.FMTime && x.FMType == 1 && !x.FDeleted)) > 0 ? true : false;

                                DateTime d1 = new DateTime(menu.FMTime.Year, menu.FMTime.Month, menu.FMTime.Day, int.Parse(lunch_start.Split(':')[0]), int.Parse(lunch_start.Split(':')[1]), 0);
                                DateTime d2 = new DateTime(menu.FMTime.Year, menu.FMTime.Month, menu.FMTime.Day, int.Parse(lunch_end.Split(':')[0]), int.Parse(lunch_end.Split(':')[1]), 0);
                                item.LSign = (await _SignIn.CountAsync(c => c.FEId == input.UserId && c.CreateTime >= d1 && c.CreateTime <= d2)) > 0 ? true : false;


                                DateTime dt = Convert.ToDateTime(item.MTime + " " + lunchTime);
                                DateTime dt2 = DateTime.Now;
                                TimeSpan t3 = dt - dt2;
                                double getDay = t3.TotalDays;
                                if (getDay < 0)
                                {
                                    item.CanLRep = false;
                                }
                                else
                                {
                                    item.CanLRep = true;
                                }
                            }
                        }
                    }
                    if (list.Count > 0)
                    {
                        foreach (var item in menus)
                        {
                            var l = list.Where(x => x.FMTime == DateTime.Parse(item.MTime) && x.FMType == 2).FirstOrDefault();
                            if (l != null)
                            {
                                item.MName4 = l.FMName;
                                item.MName5 = l.FMName2;
                                item.MName6 = l.FMName3;
                                item.Soup2 = l.FSoup;
                                item.DRep = await _MealReporting.CountAsync(x => x.FEID == input.UserId && x.FRTime == l.FMTime && x.FMType == 2 && !x.FDeleted) > 0 ? true : false;
                                item.DWorkOver = (await _MealReporting.GetFirstAsync(x => x.FEID == input.UserId && x.FRTime == l.FMTime && x.FMType == 2 && !x.FDeleted))?.FWorkOver;
                                var t = await _MealReporting.GetFirstAsync(x => x.FEID == input.UserId && x.FRTime == l.FMTime && x.FMType == 2 && !x.FDeleted);
                                DateTime d3 = new DateTime(l.FMTime.Year, l.FMTime.Month, l.FMTime.Day, int.Parse(dinner_start.Split(':')[0]), int.Parse(dinner_start.Split(':')[1]), 0);
                                DateTime d4 = new DateTime(l.FMTime.Year, l.FMTime.Month, l.FMTime.Day, int.Parse(dinner_end.Split(':')[0]), int.Parse(dinner_end.Split(':')[1]), 0);
                                item.DSign = await _SignIn.CountAsync(c => c.FEId == input.UserId && c.CreateTime >= d3 && c.CreateTime <= d4) > 0 ? true : false;


                                DateTime dt = Convert.ToDateTime(item.MTime + " " + dinnerTime);
                                DateTime dt2 = DateTime.Now;
                                TimeSpan t3 = dt - dt2;
                                double getDay = t3.TotalDays;
                                if (getDay < 0)
                                {
                                    item.CanDRep = false;
                                }
                                else
                                {
                                    item.CanDRep = true;
                                }
                            }
                        }
                    }
                }
                Util.NLOG.LogHelper.Info(JsonConvert.SerializeObject(menus));
                for (int i = menus.Count - 1; i >= 0; i--)
                {
                    var item = menus[i];
                    if (item.MName == "" && item.MName2 == "" && item.MName3 == "" && item.MName4 == "" && item.MName5 == "" && item.MName6 == "")
                    {
                        menus.Remove(item);
                    }
                }

                return result.Success(menus);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetMeenDay:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取当前周菜单(食堂员工查看)
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<CanteenMenuOutput>>> GetCanteenMeenList()
        {
            ResultMsg<List<CanteenMenuOutput>> result = new ResultMsg<List<CanteenMenuOutput>>();
            try
            {
                DateTime dTime = DateTime.Now;
                int dayofweek = -1 * (int)dTime.DayOfWeek;
                DateTime weekStartTime = dTime.AddDays(dayofweek + 1);//取本周一
                DateTime weekEndTime = dTime.AddDays(dayofweek + +6);//取本周一
                if (dayofweek == 0) //如果今天是周日，则开始时间是上周一
                {
                    weekStartTime = weekStartTime.AddDays(-7);
                }
                var list = (await _CanteenMenu.GetListAsync(x => x.FMTime >= weekStartTime.Date && x.FMTime <= weekEndTime.Date)).Select(a => new CanteenMenuOutput
                {
                    MName = a.FMName,
                    MTime = a.FMTime,
                    MName2 = a.FMName2,
                    MName3 = a.FMName3,
                    MType = a.FMType,
                    Soup = a.FSoup,
                    WeekDay = GetWeek((int)a.FMTime.DayOfWeek)
                }).OrderBy(c => new { c.MTime, c.MType }).ToList();
                foreach (var item in list)
                {
                    item.Reportings = await _MealReporting.CountAsync(c => c.FRTime == item.MTime && c.FMType == item.MType);
                }
                return result.Success(list);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetMeenDay:" + ex);
                return result.Exception();
            }
            string GetWeek(int dayofweek)
            {
                string str = string.Empty;
                switch (dayofweek)
                {
                    case 0:
                        str = "星期日";
                        break;
                    case 1:
                        str = "星期一";
                        break;
                    case 2:
                        str = "星期二";
                        break;
                    case 3:
                        str = "星期三";
                        break;
                    case 4:
                        str = "星期四";
                        break;
                    case 5:
                        str = "星期五";
                        break;
                    case 6:
                        str = "星期六";
                        break;
                    default:
                        break;
                }
                return str;
            }
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<List<AllCanteenMenuOutput>>> GetAll(CanteenMenuGetAllInput input)
        {
            ResultMsg<List<AllCanteenMenuOutput>> result = new ResultMsg<List<AllCanteenMenuOutput>>();
            try
            {
                var list = new List<tCanteenMenu>();
                List<AllCanteenMenuOutput> menus = new List<AllCanteenMenuOutput>();
                AllCanteenMenuOutput dao = new AllCanteenMenuOutput();
                if (input != null)
                {
                    if (input.STime > input.EndTime)
                    {
                        return result.Error("开始时间不能大于结束时间");
                    }
                    if (DateTime.Compare(input.EndTime, input.STime) < 7)
                    {
                        input.EndTime = input.EndTime.AddDays(DateTime.Compare(input.EndTime, input.STime));
                    }


                    menus.Insert(0, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.DayOfWeek),
                        MTime = input.STime.ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(1, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(1).DayOfWeek),
                        MTime = input.STime.AddDays(1).ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(2, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(2).DayOfWeek),
                        MTime = input.STime.AddDays(2).ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(3, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(3).DayOfWeek),
                        MTime = input.STime.AddDays(3).ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(4, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(4).DayOfWeek),
                        MTime = input.STime.AddDays(4).ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(5, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(5).DayOfWeek),
                        MTime = input.STime.AddDays(5).ToString("yyyy-MM-dd"),
                    });
                    menus.Insert(6, new AllCanteenMenuOutput
                    {
                        WeekDay = getWeekDay(input.STime.AddDays(6).DayOfWeek),
                        MTime = input.STime.AddDays(6).ToString("yyyy-MM-dd"),
                    });
                    list = await _CanteenMenu.GetListAsync(x => x.FMTime >= input.STime && x.FMTime <= input.EndTime);
                    foreach (var item in menus)
                    {
                        if (menus.Select(c => c.MTime).Contains(item.MTime))
                        {
                            foreach (var menu in list.Where(x => x.FMType == 1))
                            {
                                if (Convert.ToDateTime(item.MTime) == menu.FMTime)
                                {
                                    item.WeekDay = menu.FWeekDay;
                                    item.MTime = menu.FMTime.ToString("yyyy-MM-dd");
                                    item.MName = menu.FMName;
                                    item.MName2 = menu.FMName2;
                                    item.MName3 = menu.FMName3;
                                    item.Soup = menu.FSoup;
                                    item.Syrup = menu.FSyrup;
                                }
                            }
                        }
                    }
                    if (list.Count > 0)
                    {
                        foreach (var item in menus)
                        {
                            if (menus.Select(c => c.MTime).Contains(item.MTime))
                            {
                                var l = list.Where(x => x.FMTime == DateTime.Parse(item.MTime) && x.FMType == 2).FirstOrDefault();
                                if (l != null)
                                {
                                    item.MName4 = l.FMName;
                                    item.MName5 = l.FMName2;
                                    item.MName6 = l.FMName3;
                                    item.Soup2 = l.FSoup;
                                }
                            }
                        }
                    }
                }
                menus = menus.OrderBy(c => c.MTime).ToList();
                List<AllCanteenMenuOutput> newList = new List<AllCanteenMenuOutput>();
                newList.Insert(0, new AllCanteenMenuOutput
                {
                    MTime = "午餐",
                    WeekDay = "晚餐"
                });
                newList.InsertRange(1, menus);

                return result.Success(newList);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetAll:" + ex);
                return result.Exception();
            }
            string getWeekDay(DayOfWeek dayOfWeek)
            {
                string str = string.Empty;
                switch (dayOfWeek)
                {
                    case DayOfWeek.Sunday:
                        str = "星期天";
                        break;
                    case DayOfWeek.Monday:
                        str = "星期一";
                        break;
                    case DayOfWeek.Tuesday:
                        str = "星期二";
                        break;
                    case DayOfWeek.Wednesday:
                        str = "星期三";
                        break;
                    case DayOfWeek.Thursday:
                        str = "星期四";
                        break;
                    case DayOfWeek.Friday:
                        str = "星期五";
                        break;
                    case DayOfWeek.Saturday:
                        str = "星期六";
                        break;
                    default:
                        str = "";
                        break;
                }
                return str;
            }
        }

        /// <summary>
        /// 食堂菜单看板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<List<AllCanteenMenuOutput>>> CantmeenBoard()
        {
            ResultMsg<List<AllCanteenMenuOutput>> result = new ResultMsg<List<AllCanteenMenuOutput>>();
            try
            {
                var list = new List<tCanteenMenu>();
                List<AllCanteenMenuOutput> menus = new List<AllCanteenMenuOutput>();
                AllCanteenMenuOutput dao = new AllCanteenMenuOutput();

                //获取当前日期
                DateTime currentDate = DateTime.Now;
                //获取当前日期星期  
                DayOfWeek dayOfWeek = currentDate.DayOfWeek;
                //本周开始日期
                DateTime startDate;
                if (dayOfWeek == DayOfWeek.Monday)
                {
                    startDate = currentDate;
                }
                else
                {
                    startDate = currentDate.AddDays(1 - (int)dayOfWeek);
                }
                //获取本周结束日期
                DateTime endDate = startDate.AddDays(6);

                menus.Insert(0, new AllCanteenMenuOutput
                {
                    WeekDay = "午餐",
                    MName = "晚餐"
                });
                menus.Insert(1, new AllCanteenMenuOutput
                {
                    WeekDay = "星期一",
                    MTime = startDate.ToString("yyyy-MM-dd"),
                });
                menus.Insert(2, new AllCanteenMenuOutput
                {
                    WeekDay = "星期二",
                    MTime = startDate.AddDays(1).ToString("yyyy-MM-dd"),
                });
                menus.Insert(3, new AllCanteenMenuOutput
                {
                    WeekDay = "星期三",
                    MTime = startDate.AddDays(2).ToString("yyyy-MM-dd"),
                });
                menus.Insert(4, new AllCanteenMenuOutput
                {
                    WeekDay = "星期四",
                    MTime = startDate.AddDays(3).ToString("yyyy-MM-dd"),
                });
                menus.Insert(5, new AllCanteenMenuOutput
                {
                    WeekDay = "星期五",
                    MTime = startDate.AddDays(4).ToString("yyyy-MM-dd"),
                });
                menus.Insert(6, new AllCanteenMenuOutput
                {
                    WeekDay = "星期六",
                    MTime = startDate.AddDays(5).ToString("yyyy-MM-dd"),
                });
                menus.Insert(7, new AllCanteenMenuOutput
                {
                    WeekDay = "星期日",
                    MTime = startDate.AddDays(6).ToString("yyyy-MM-dd"),
                });
                list = await _CanteenMenu.GetListAsync(x => x.FMTime >= startDate.Date && x.FMTime <= endDate.Date);
                foreach (var item in menus)
                {
                    if (menus.IndexOf(item) != 0)
                    {
                        foreach (var menu in list.Where(x => x.FMType == 1))
                        {
                            if (item.WeekDay == menu.FWeekDay)
                            {
                                item.WeekDay = menu.FWeekDay;
                                item.MTime = menu.FMTime.ToString("yyyy-MM-dd");
                                item.MName = menu.FMName;
                                item.MName2 = menu.FMName2;
                                item.MName3 = menu.FMName3;
                                item.Soup = menu.FSoup;
                                item.Syrup = menu.FSyrup;
                            }
                        }
                    }
                }
                if (list.Count > 0)
                {
                    foreach (var item in menus)
                    {
                        if (menus.IndexOf(item) != 0)
                        {
                            var l = list.Where(x => x.FMTime == DateTime.Parse(item.MTime) && x.FMType == 2).FirstOrDefault();
                            if (l != null)
                            {
                                item.MName4 = l.FMName;
                                item.MName5 = l.FMName2;
                                item.MName6 = l.FMName3;
                                item.Soup2 = l.FSoup;
                            }
                        }
                    }
                }
                foreach (var item in menus)
                {
                    if (item.WeekDay == GetWeek())
                    {
                        int lunch = await _MealReporting.CountAsync(x => !x.FDeleted && x.FMType == 1 && x.FRTime.ToString("yyyy-MM-dd") == item.MTime);
                        int dinner = await _MealReporting.CountAsync(x => !x.FDeleted && x.FMType == 2 && x.FRTime.ToString("yyyy-MM-dd") == item.MTime);
                        item.WeekDay += string.Format("<br>午餐{0}人<br>晚餐{1}人", lunch, dinner);
                    }
                }
                string GetWeek()
                {
                    string week = string.Empty;
                    switch (dayOfWeek.ToString())
                    {
                        case "Monday":
                            week = "星期一";
                            break;
                        case "Tuesday":
                            week = "星期二";
                            break;
                        case "Wednesday":
                            week = "星期三";
                            break;
                        case "Thursday":
                            week = "星期四";
                            break;
                        case "Friday":
                            week = "星期五";
                            break;
                        case "Saturday":
                            week = "星期六";
                            break;
                        case "Sunday":
                            week = "星期日";
                            break;
                    }
                    return week;
                }

                return result.Success(menus);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetAll:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取当天菜单以及报餐人数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<GetTodayMeenOutput>> GetTodayMeen(DateTime dt)
        {
            ResultMsg<GetTodayMeenOutput> result = new ResultMsg<GetTodayMeenOutput>();
            try
            {
                GetTodayMeenOutput dao = new GetTodayMeenOutput();
                var model = await _CanteenMenu.GetFirstAsync(x => x.FMTime == dt.Date && x.FMType == 1);
                if (model != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.FMName))
                    {
                        dao.LunchMeen += model.FMName;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FMName2))
                    {
                        dao.LunchMeen += "," + model.FMName2;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FMName3))
                    {
                        dao.LunchMeen += "," + model.FMName3;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FSoup))
                    {
                        dao.LunchMeen += "," + model.FSoup;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FSyrup))
                    {
                        dao.LunchMeen += "," + model.FSyrup;
                    }
                }
                model = await _CanteenMenu.GetFirstAsync(x => x.FMTime == dt.Date && x.FMType == 2);
                if (model != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.FMName))
                    {
                        dao.DinnerMeen += model.FMName;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FMName2))
                    {
                        dao.DinnerMeen += "," + model.FMName2;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FMName3))
                    {
                        dao.DinnerMeen += "," + model.FMName3;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FSoup))
                    {
                        dao.DinnerMeen += "," + model.FSoup;
                    }
                    if (!string.IsNullOrWhiteSpace(model.FSyrup))
                    {
                        dao.DinnerMeen += "," + model.FSyrup;
                    }
                }
                dao.LunchNum = await _MealReporting.CountAsync(x => x.FMType == 1 && !x.FDeleted && x.FRTime == dt.Date);
                dao.DinnerNum = await _MealReporting.CountAsync(x => x.FMType == 2 && !x.FDeleted && x.FRTime == dt.Date);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetTodayMeen:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取食材类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultMsg<List<GetFoodTypeOutput>> GetFoodType()
        {
            ResultMsg<List<GetFoodTypeOutput>> result = new ResultMsg<List<GetFoodTypeOutput>>();
            try
            {
                string path = string.Empty;
                path = AppContext.BaseDirectory + "\\foodType.json";
                JArray ja = null;
                List<GetFoodTypeOutput> list = null;
                using (StreamReader sr = new StreamReader(path))
                {
                    try
                    {
                        ja = JArray.Parse(sr.ReadToEnd());

                        list = ja.ToObject<List<GetFoodTypeOutput>>();


                    }
                    catch (Exception ex)
                    {

                    }
                    sr.Close();
                }
                return result.Success(list);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetFoodType:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 采购月汇总
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultMsg<FoodProcureMonthlySummaryOutput> FoodProcureMonthlySummary(FoodProcureMonthlySummaryInput input)
        {
            ResultMsg<FoodProcureMonthlySummaryOutput> result = new ResultMsg<FoodProcureMonthlySummaryOutput>();
            try
            {
                var startDate = input.SMonth;
                var endDate = input.SMonth.AddMonths(1).AddDays(-1);
                string strSql = string.Empty;
                //strSql = string.Format("select CONVERT(varchar(100), tab.ProcureDate, 23) as Day,datename(weekday,tab.ProcureDate) as Week, tab.meat,tab.aquaculture,tab.CanteenType,tab.dish,tab.fivecereals,tab.other,tab.poultry,tab.seasoning,tab.meat+tab.poultry+tab.aquaculture+tab.dish+tab.fivecereals+tab.seasoning+tab.other as DayStatistics from(\r\nselect a.*,(select ISNULL(SUM(b.TotalPrice),0) from tFoodProcure b where b.CanteenType=a.CanteenType and b.ProcureDate=a.ProcureDate and b.FType=1) as meat\r\n,(select ISNULL(SUM(c.TotalPrice),0) from tFoodProcure c where c.CanteenType=a.CanteenType and c.ProcureDate=a.ProcureDate and c.FType=2) as poultry\r\n,(select ISNULL(SUM(d.TotalPrice),0) from tFoodProcure d where d.CanteenType=a.CanteenType and d.ProcureDate=a.ProcureDate and d.FType=3) as aquaculture\r\n,(select ISNULL(SUM(e.TotalPrice),0) from tFoodProcure e where e.CanteenType=a.CanteenType and e.ProcureDate=a.ProcureDate and e.FType=4) as dish\r\n,(select ISNULL(SUM(f.TotalPrice),0) from tFoodProcure f where f.CanteenType=a.CanteenType and f.ProcureDate=a.ProcureDate and f.FType=5) as fivecereals\r\n,(select ISNULL(SUM(g.TotalPrice),0) from tFoodProcure g where g.CanteenType=a.CanteenType and g.ProcureDate=a.ProcureDate and g.FType=6) as seasoning\r\n,(select ISNULL(SUM(h.TotalPrice),0) from tFoodProcure h where h.CanteenType=a.CanteenType and h.ProcureDate=a.ProcureDate and h.FType=7) as other\r\nfrom\r\n(select t.ProcureDate,t.CanteenType from tFoodProcure t where t.ProcureDate >= '{0}' and t.ProcureDate<='{1}' group by t.ProcureDate,t.CanteenType)\r\na) tab ", startDate,endDate);
                //string strWhere = string.Format(" where 1=1  and tab.CanteenType={0}", input.CantmeenType);
                strSql = $@"
                    select CONVERT(VARCHAR(10), a.FRTime, 120) as Day,DATENAME(WEEKDAY, a.FRTime) as Week,(select count(0) from tMealReporting b where b.FRTime=a.FRTime and b.FMType=1) as Lunch,
    (select count(0) from tMealReporting c where c.FRTime=a.FRTime and c.FMType=2) as Dinner 
    from tMealReporting a 
    where FRTime>='{startDate}' and FRTime<='{endDate}' 
group by FRTime order by FRTime desc";

                var list = _db.Ado.SqlQuery<Summary>(strSql);
                Common commonInstance = new Common(_db); // 使用db实例化Common类
                var lunch_start = commonInstance.GetConfig().LunchStartScan;
                var lunch_end = commonInstance.GetConfig().LunchEndScan;
                var dinner_start = commonInstance.GetConfig().DinnerStartScan;
                var dinner_end = commonInstance.GetConfig().DinnerEndScan;

                DateTime LunchStartScan = new DateTime();
                DateTime LunchEndScan = new DateTime();
                DateTime DinnerStartScan = new DateTime();
                DateTime DinnerEndScan = new DateTime();

                foreach (var item in list)
                {
                    item.DayStatistics = item.Lunch + item.Dinner;

                    LunchStartScan = DateTime.Parse(item.Day + " " + lunch_start);
                    LunchEndScan = DateTime.Parse(item.Day + " " + lunch_end);
                    DinnerStartScan = DateTime.Parse(item.Day + " " + dinner_start);
                    DinnerEndScan = DateTime.Parse(item.Day + " " + dinner_end);
                    item.EatLunch = _SignIn.GetList(x => x.CreateTime >= LunchStartScan && x.CreateTime <= LunchEndScan).Count();
                    item.EatDinner = _SignIn.GetList(x => x.CreateTime >= DinnerStartScan && x.CreateTime <= DinnerEndScan).Count();
                    item.DayEatStatistics = item.EatDinner + item.EatLunch;
                }
                FoodProcureMonthlySummaryOutput dao = new FoodProcureMonthlySummaryOutput();
                dao.List = list;
                dao.Num = list.Sum(c => c.Lunch) + list.Sum(c => c.Dinner);
                dao.EatNum = list.Sum(c => c.EatLunch) + list.Sum(c => c.EatDinner);
                //dao.Total = list.Sum(c=>c.DayStatistics);

                dao.Total = Convert.ToDecimal(_food.GetList(x => x.FProcureDate >= startDate && x.FProcureDate <= endDate).Sum(c => c.FPrice));
                dao.Meals = dao.Num != 0 ? Math.Round(dao.Total / dao.Num, 2) : 0;

                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenMenuController-GetFoodType:" + ex);
                return result.Exception();
            }
        }
    }
}
